package org.example.filter;

import io.jsonwebtoken.Claims;
import org.example.exception.CunstomAuthenticationException;
import org.example.model.LoginUserDetails;
import org.example.utils.JwtUtils;
import org.example.utils.Redisconstant;
import org.example.utils.ResponseResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @author Rommel
 * @version 1.0
 * @date 2023/6/18-21:40
 * @description TODO
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private RedisTemplate redisTemplate;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            doFilter(request,response,filterChain);
        } catch (Exception e) {
            ResponseResult.exceptionResponse(response,e);
        }
    }

    private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException{
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String username;
        try {
            Claims claims = JwtUtils.parseJwt(token,JwtUtils.base64EncodedSecretKey);
            Date now = new Date();
            if (now.getTime() > claims.getExpiration().getTime()) {
                throw new CunstomAuthenticationException("登录已过期,请重新登陆");
            }
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CunstomAuthenticationException("token非法");
        }

        LoginUserDetails loginUserDetails = (LoginUserDetails)userDetailsService.loadUserByUsername(username);
        if(Objects.isNull(loginUserDetails)){
            throw new CunstomAuthenticationException("账号信息不存在");
        }
        //继续判断token有效性
        Object tokenObject = redisTemplate.opsForValue().get(Redisconstant.LOGIN_SYS_USER_TOKEN_WEB_KEY+loginUserDetails.getUserid());
        if(Objects.isNull(tokenObject)){
            throw new CunstomAuthenticationException("用户未登录");
        }
        if(!token.equals(tokenObject.toString())){
            throw new CunstomAuthenticationException("无效token");
        }

        //构建UsernamePasswordAuthenticationToken对象
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(loginUserDetails,null,loginUserDetails.getAuthorities());
        //将authenticationToken对象放入SecurityContextHolder上下文中
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}